<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadFile,
  type UploadInstance,
  type UploadProps,
  type UploadRawFile,
} from 'element-plus'
import { Delete, Edit, Plus, Search, Refresh } from '@element-plus/icons-vue'
import type { User, UserAddRequest, UserQueryRequest } from '@/api-client/src/api-client/models'
import { getUserController } from '@/api-client/src/api-client/user-controller/user-controller'
import { axiosInstance } from '@/axios-instance'

// 为API响应定义一个标准类型，因为我们是直接调用axios实例
interface ApiResponse<T = unknown> {
  code: number
  data: T
  message: string
}

const userApi = getUserController()

const loading = ref(false)
const userList = ref<User[]>([])
const total = ref(0)
const selectedUsers = ref<User[]>([])

// 搜索表单
const searchForm = reactive<UserQueryRequest>({
  current: 1,
  pageSize: 10,
  userName: '',
  type: undefined,
})

// --- 对话框状态 ---
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => (isEdit.value ? '编辑用户' : '新增用户'))
const userFormRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()

// 对话框表单
const userForm = ref<Partial<User>>({
  id: undefined,
  userName: '',
  type: 2, // 默认为普通用户
  remarks: '',
})

// 文件上传列表
const fileList = ref<UploadFile[]>([])
// 图片预览
const previewImageUrl = ref('')
const previewDialogVisible = ref(false)

// 表单校验规则
const rules = reactive<FormRules<typeof userForm>>({
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  type: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
})

const fetchData = async () => {
  loading.value = true
  try {
    const res = await userApi.queryUserByPage(searchForm)
    if (res.code === 200 && res.data) {
      userList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch {
    ElMessage.error('网络错误，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取初始数据
onMounted(fetchData)

/**
 * 处理搜索
 */
const handleSearch = () => {
  searchForm.current = 1 // 重置到第一页
  fetchData()
}

/**
 * 处理重置搜索表单
 */
const handleReset = () => {
  searchForm.userName = ''
  searchForm.type = undefined
  handleSearch()
}

/**
 * 处理分页大小变化
 * @param val 每页数量
 */
const handleSizeChange = (val: number) => {
  searchForm.pageSize = val
  fetchData()
}

/**
 * 处理当前页变化
 * @param val 当前页码
 */
const handleCurrentChange = (val: number) => {
  searchForm.current = val
  fetchData()
}

/**
 * 处理表格多选变化
 * @param selection 选中的行
 */
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection
}

/**
 * 打开新增用户对话框
 */
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

/**
 * 打开编辑用户对话框
 * @param row 用户数据
 */
const handleEdit = (row: User) => {
  isEdit.value = true
  resetForm()
  // 深拷贝，避免直接修改表格数据
  userForm.value = JSON.parse(JSON.stringify(row))
  // 编辑时不显示已有头像，保持上传框为空状态
  fileList.value = []
  dialogVisible.value = true
}

/**
 * 处理单个删除
 * @param row 用户数据
 */
const handleDelete = (row: User) => {
  ElMessageBox.confirm(`确定要删除用户【${row.userName}】吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      if (!row.id) return
      const res = await userApi.deleteUser({ id: row.id })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        await fetchData()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

/**
 * 处理批量删除
 */
const handleBatchDelete = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一个用户')
    return
  }
  ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const ids = selectedUsers.value.map((user) => user.id).filter((id) => id) as number[]
      if (ids.length === 0) return
      const res = await userApi.deleteUserBatch(ids)
      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        await fetchData()
      } else {
        ElMessage.error(res.message || '批量删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

/**
 * 处理对话框提交
 */
const handleDialogSubmit = async () => {
  if (!userFormRef.value) return
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑逻辑
        if (!userForm.value.id) {
          ElMessage.error('用户ID不存在，无法更新')
          return
        }
        const formData = new FormData()
        // 表单校验保证了 userName 和 type 必填
        formData.append('id', String(userForm.value.id))
        formData.append('userName', userForm.value.userName!)
        formData.append('type', String(userForm.value.type!))
        formData.append('remarks', userForm.value.remarks || '')

        // 如果有新上传的文件(raw存在)，则添加到formData
        const newFile = fileList.value.find((file) => file.raw)
        if (newFile && newFile.raw) {
          formData.append('avatar', newFile.raw)
        }

        try {
          // 由于需要上传文件(multipart/form-data)，我们直接使用axios实例来发送请求
          // 并为响应指定 ApiResponse 类型
          const response = await axiosInstance<ApiResponse>({
            url: `/user/update/${userForm.value.id}`,
            method: 'PUT',
            data: formData,
          })

          // axios实例可能配置了拦截器，直接返回响应体(ApiResponse)，所以我们直接访问 response.code
          if (response && response.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            await fetchData()
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        } catch (error) {
          console.error('更新用户时出错:', error)
          ElMessage.error('网络错误，更新失败')
        }
      } else {
        // 新增逻辑
        const addUserRequest: UserAddRequest = {
          userName: userForm.value.userName,
          type: userForm.value.type,
          remarks: userForm.value.remarks,
        }
        const res = await userApi.addUser(addUserRequest)
        if (res.code === 200) {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          await fetchData()
        } else {
          ElMessage.error(res.message || '新增失败')
        }
      }
    } else {
      ElMessage.error('请检查表单项是否填写正确')
    }
  })
}

/**
 * 重置对话框表单
 */
const resetForm = () => {
  userForm.value = {
    id: undefined,
    userName: '',
    type: 2,
    remarks: '',
  }
  fileList.value = []
  userFormRef.value?.resetFields()
  uploadRef.value?.clearFiles()
}

// --- 文件上传处理 ---

/**
 * 上传前校验
 * @param rawFile 文件
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {
  const isImage = ['image/svg+xml', 'image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)
  const isLt5M = rawFile.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('头像必须是图片格式 (SVG, JPG, PNG, GIF)!')
  }
  if (!isLt5M) {
    ElMessage.error('头像图片大小不能超过 5MB!')
  }
  return isImage && isLt5M
}

/**
 * 处理移除图片
 */
const handleRemove: UploadProps['onRemove'] = () => {
  fileList.value = []
}

/**
 * 处理超出文件数量限制
 * @param files
 */
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  uploadRef.value!.handleStart(file)
}

/**
 * 处理图片预览
 * @param uploadFile
 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  previewImageUrl.value = uploadFile.url!
  previewDialogVisible.value = true
}

/**
 * 处理头像选择变化
 * @param uploadFile
 * @param uploadFiles
 */
const handleAvatarChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  // 确保只保留最新选择的文件
  fileList.value = uploadFiles.slice(-1)
}

// --- 辅助函数 ---

/**
 * 格式化用户类型
 * @param type 类型值
 */
const formatUserType = (type: number | undefined) => {
  if (type === 1) return '管理员'
  if (type === 2) return '普通用户'
  return '未知'
}
</script>

<template>
  <div class="user-view">
    <!-- 搜索与操作区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择用户类型"
            clearable
            style="width: 200px"
          >
            <el-option label="管理员" :value="1" />
            <el-option label="普通用户" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-card">
      <div class="action-buttons">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增用户</el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="userList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userName" label="用户名" min-width="150" align="center" />
        <el-table-column prop="avatar" label="头像" width="100" align="center">
          <template #default="{ row }">
            <el-avatar :size="50" :src="row.avatar">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="用户类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type === 1 ? 'success' : 'info'">{{
              formatUserType(row.type)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" text @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button type="danger" :icon="Delete" size="small" text @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        :current-page="searchForm.current"
        :page-size="searchForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="550px" @close="resetForm">
      <el-form ref="userFormRef" :model="userForm" :rules="rules" label-width="auto">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-radio-group v-model="userForm.type">
            <el-radio :value="1">管理员</el-radio>
            <el-radio :value="2">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="userForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item v-if="isEdit" label="头像">
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :limit="1"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload"
            :on-exceed="handleExceed"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleAvatarChange"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png/gif/svg文件，且不超过5MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDialogSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible">
      <img :src="previewImageUrl" alt="Preview Image" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<style scoped>
.user-view {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-card,
.table-card {
  border-radius: 8px;
}

.action-buttons {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>
